<?php

namespace App\Http\Controllers\Api\v1;

use App\Models\Archive;
use App\Models\Article;
use App\Transformers\ArchiveTransformer;
use App\Utils\Tool;
use Illuminate\Http\Request;

class ArchiveController extends BaseController
{
    /**
     * Instanceof ArchiveTransformer
     *
     * @var ArchiveTransformer
     */
    private $transformer;

    /**
     * ArchiveController constructor.
     * @param ArchiveTransformer $transformer
     */
    public function __construct(ArchiveTransformer $transformer)
    {
        $this->transformer = $transformer;
    }

    /**
     * @param Request $request
     * @return \Dingo\Api\Http\Response
     */
    public function index(Request $request)
    {
        $perPage = $request->get('perPage', 5);
        $list = Article::query()
            ->selectRaw('DATE_FORMAT(\'%Y-%m\',created_at) as date')
            ->where(['status' => Article::STATUS_PUBLISHED])
            ->groupBy('date')
            ->orderBy('date', 'desc')
            ->pluck('date')->toArray();
        $archives = collect();
        foreach ($list as $date) {
            $archives->push(new Archive($date));
        }
        $archives = Tool::paginate($archives->toArray(), $perPage);
        return $this->response->paginator($archives, $this->transformer);

    }

    /**
     * @param $date
     * @return \Dingo\Api\Http\Response
     */
    public function show($date)
    {
        $archive = new Archive($date);
        return $this->response->item($archive, $this->transformer);
    }

}